﻿using System;
using System.Collections.Generic;

namespace Cmpp.Client.Cmpp3Message.Utility {
    public class CmppMessageWriter {
        private readonly List<byte> m_data;

        public CmppMessageWriter() {
            m_data = new List<byte>(1024);
        }

        public CmppMessageWriter(IEnumerable<byte> data) {
            m_data = new List<byte>(1024);

            m_data.AddRange(data);
        }

        public long Length {
            get {
                return m_data.Count;
            }
        }

        public void Write(string text) {
            byte[] bytes = DataConvert.StringToBytes(text);
            m_data.AddRange(bytes);
        }

        public void Write(string text, PaddingType paddingType, int lenght) {
            string paddingText;
            if (paddingType == PaddingType.Right) {
                paddingText = text.PadRight(lenght, '\0');
            }
            else {
                paddingText = text.PadLeft(lenght, '0');
            }

            if(paddingText.Length > lenght) {
                paddingText = paddingText.Substring(0, lenght);
            }

            byte[] bytes = DataConvert.StringToBytes(paddingText);
            m_data.AddRange(bytes);
        }

        public void Write(uint value) {
            value = DataConvert.HostToNetworkOrderExchange(value);
            byte[] bytes = BitConverter.GetBytes(value);
            m_data.AddRange(bytes);
        }

        public void Write(ulong value) {
            value = DataConvert.HostToNetworkOrderExchange(value);
            byte[] bytes = BitConverter.GetBytes(value);
            m_data.AddRange(bytes);
        }

        public void Write(byte value) {
            m_data.Add(value);
        }

        public void Write(bool value) {
            if(value) {
                m_data.Add(1);
            }
            else {
                m_data.Add(0);
            }
        }

        public void Write(byte[] value) {
            m_data.AddRange(value);
        }

        public byte[] ToBytes() {
            return m_data.ToArray();
        }

        //private static byte[] HostByteToNetwork(byte[] byteHost) {
        //    byte[] byteNetwork = new Byte[byteHost.Length];
        //    for (int i = 0; i < byteHost.Length; i++)
        //    {
        //        byteNetwork[byteHost.Length - i - 1] = byteHost[i];
        //    }
        //    return byteNetwork;
        //}
    }

    public enum PaddingType {
        Left = 0,
        Right = 1
    }
}